package com.shop.filter;


import com.shop.util.TransactionManager;

import javax.servlet.*;
import java.io.IOException;

/**
 * 事务控制过滤器
 */
public class TransactionFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        try {
            TransactionManager.beginTransaction();
            //执行当次请求
            filterChain.doFilter(servletRequest,servletResponse);
            //执行完成提交事务
            TransactionManager.commit();
        }catch (Exception e){
            TransactionManager.rollback();
            e.printStackTrace();
            throw new RuntimeException(e);
        }finally {
            TransactionManager.release();
        }
    }

    @Override
    public void destroy() {

    }
}
